<template>
  <component width="550px" :is="componentId" v-model="show" direction="rtl" :before-close="beforeClose">
    <template #header>
      <h4>{{ title ? title : modelValue && modelValue.id ? '编辑' : '新增' }}</h4>
    </template>
    <template #default>
      <el-form ref="formRef" :model="modelValue" label-width="120px" v-bind="formProps">
        <jax-form-group v-model="modelValue" :json="json">
          <template v-for="slotName in Object.keys($slots)" v-slot:[slotName]="item">
            <slot :name="slotName" v-bind="item"></slot>
          </template>
        </jax-form-group>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </component>
</template>

<script>
export default {
  name: 'jax-dialog-edit',
}
</script>
<script setup>
const props = defineProps({
  modelValue: { type: Object, default: () => {} },
  type: { type: String, default: 'dialog' }, // 类型 dialog、drawer
  show: Boolean,
  json: Object,
  title: String,
  formProps: { type: Object, default: () => {} },
})
const emit = defineEmits(['submit', 'update:show'])

const formRef = ref()
const componentId = computed(() => {
  const components = {
    dialog: 'el-dialog',
    drawer: 'el-drawer',
  }

  return components[props.type] || 'el-dialog'
})

// 取消
function handleCancel() {
  emit('update:show', false)
}

// 保存
function handleSubmit() {
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        emit('submit', false)
      }
    })
  } else {
    emit('submit', false)
  }
}

// 关闭前
function beforeClose(callback) {
  handleCancel()
  callback()
}
</script>
